/*
 *Copyright 2021-2023 NERCIS
 *
 *Licensed under the Apache License, Version 2.0 (the "License");
 *you may not use this file except in compliance with the License.
 *You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 *Unless required by applicable law or agreed to in writing, software
 *distributed under the License is distributed on an "AS IS" BASIS,
 *WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *See the License for the specific language governing permissions and
 *limitations under the License.
 */

package cn.ac.nercis.pes.service.project.imported;

import cn.ac.nercis.pes.model.dto.common.Result;
import cn.ac.nercis.pes.model.dto.project.ImportConflictDTO;
import cn.ac.nercis.pes.model.standard.prepare.EvaluationProcessSDTO;
import cn.ac.nercis.pes.repository.dal.evaluation.EvaluationProcessRepository;
import cn.ac.nercis.pes.repository.model.evaluation.EvaluationProcessDO;
import cn.ac.nercis.pes.service.utils.CheckFieldUtils;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 测评过程数据导入服务
 *
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
@Service
public class EvaluationProcessImportService {
    private final EvaluationProcessRepository evaluationProcessRepository;

    @Autowired
    public EvaluationProcessImportService(EvaluationProcessRepository evaluationProcessRepository) {
        this.evaluationProcessRepository = evaluationProcessRepository;
    }

    public Result<List<ImportConflictDTO>> checkEvaluationProcessData(@NonNull String systemId, List<EvaluationProcessSDTO> process) {
        List<EvaluationProcessDO> sourceProcess = this.evaluationProcessRepository.findAllBySystemId(systemId);
        if (CollectionUtils.isEmpty(sourceProcess)) {
            return Result.success();
        }
        List<ImportConflictDTO> conflictData = process.stream()
                .flatMap(st -> this.checkEvaluationProcessData(st, sourceProcess).stream())
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        return Result.success(conflictData);
    }

    public Result<String> importEvaluationProcessData(@NonNull String systemId, List<EvaluationProcessSDTO> process, Boolean cover) {
        List<EvaluationProcessDO> sourceProcess = this.evaluationProcessRepository.findAllBySystemId(systemId);
        Result<String> result = Result.success();
        for (EvaluationProcessSDTO p : process) {
            result = this.importEvaluationProcessData(systemId, p, sourceProcess, cover);
            if (!result.isSuccess()) {
                break;
            }
        }
        return result;
    }

    private List<ImportConflictDTO> checkEvaluationProcessData(@NonNull EvaluationProcessSDTO importProcess, List<EvaluationProcessDO> sourceProcess) {
        var processDO = sourceProcess.stream()
                .filter(st -> StringUtils.equals(st.getName(), importProcess.getName()))
                .findFirst()
                .orElse(null);
        if (Objects.isNull(processDO)) {
            return Collections.emptyList();
        }
        return CheckFieldUtils.checkField(processDO, importProcess);
    }

    private Result<String> importEvaluationProcessData(String systemId, @NonNull EvaluationProcessSDTO importProcess, List<EvaluationProcessDO> sourceProcess, Boolean cover) {
        var processDO = sourceProcess.stream()
                .filter(st -> StringUtils.equals(st.getName(), importProcess.getName()))
                .findFirst().orElse(null);
        if (Objects.isNull(processDO)) {
            return createEvaluationProcessData(systemId, importProcess,sourceProcess);
        } else {
            return modifyEvaluationProcessData(processDO, importProcess, cover);
        }
    }

    private Result<String> createEvaluationProcessData(String systemId, EvaluationProcessSDTO importProcess, List<EvaluationProcessDO> sourceProcess) {
        EvaluationProcessDO processDO = EvaluationProcessDO.builder()
                .systemId(systemId)
                .name(importProcess.getName())
                .startDate(importProcess.getStartDate())
                .endDate(importProcess.getEndDate())
                .build();
        processDO.setCreateTime(LocalDateTime.now());
        return Optional.of(processDO)
                .map(this.evaluationProcessRepository::save)
                .map(ep->{
                    sourceProcess.add(ep);
                    return Result.success(ep.getId());
                })
                .orElse(Result.failed(String.format("导入%s测评过程信息，创建失败", importProcess.getName())));
    }

    private Result<String> modifyEvaluationProcessData(EvaluationProcessDO sourceProcess, EvaluationProcessSDTO importProcess, Boolean cover) {
        sourceProcess.setStartDate(CheckFieldUtils.applyContent(sourceProcess.getStartDate(), importProcess.getStartDate(), cover));
        sourceProcess.setEndDate(CheckFieldUtils.applyContent(sourceProcess.getEndDate(), importProcess.getEndDate(), cover));
        sourceProcess.setModifyTime(LocalDateTime.now());
        return Optional.of(sourceProcess)
                .map(this.evaluationProcessRepository::save)
                .map(EvaluationProcessDO::getId)
                .map(Result::success)
                .orElse(Result.failed(String.format("导入%s测评过程信息，修改失败", importProcess.getName())));
    }

}
